<template>
  <div class="login-account">
    <I18n></I18n>
    <el-form
      @submit.prevent
      ref="formRef"
      :model="account"
      :rules="accountRules"
      class="demo-ruleForm"
    >
      <el-form-item :label-width="labelWidth" :label="$t('login.account')" prop="name">
        <el-input type="text" autocomplete="off" v-model="account.name" />
      </el-form-item>
      <el-form-item :label="$t('login.password')" prop="password">
        <el-input v-model="account.password" type="password" autocomplete="off" show-password />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import type { ElForm, FormRules } from 'element-plus'
import type { IAcount } from '@/types/login'
import useLoginStore from '@/store/modules/login'
import { localCache } from '@/utils/Cache'
import emitter from '@/utils/bus'
import I18n from '@/components/i18n/i18n.vue'
const NMAE_INFO = 'name'
const PASS_WORD = 'password'

const account = reactive<IAcount>({
  name: localCache.getCache(NMAE_INFO) ?? 'coderwhy',
  password: localCache.getCache(PASS_WORD) ?? '123456'
})

// 定义校验规则
const accountRules: FormRules = {
  name: [
    { required: true, message: '请输入账户名称', trigger: 'blur' },
    { pattern: /^[a-z0-9]{6,20}$/, message: '必须是6-20位长度', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '必须输入密码信息', trigger: 'blur' },
    { pattern: /^[a-z0-9]{3,}$/, message: '必须是3以上数字或者字母组成', trigger: 'blur' }
  ]
}

const formRef = ref<InstanceType<typeof ElForm>>()
const loginStore = useLoginStore()
// 父组件调用的方法 登录
function returnLoginData(isRemPwd: boolean) {
  formRef.value?.validate((valid) => {
    if (valid) {
      const name = account.name
      const password = account.password
      loginStore.getAccountLogin({ name, password }).then(() => {
        // 返回数据成功之后判断是否需要记住密码
        if (isRemPwd) {
          localCache.setCache(NMAE_INFO, name)
          localCache.setCache(PASS_WORD, password)
        } else {
          localCache.removeCache(NMAE_INFO)
          localCache.removeCache(PASS_WORD)
        }
      })
    } else {
      ElMessage.error('Oops, this is a error message.')
    }
  })
}

const labelWidth = ref('')
const langWidth = ref(localCache.getCache('lang'))
if (langWidth.value == 'en') {
  labelWidth.value = '85'
}
emitter.on('autoLang', (data) => {
  if (data == 'en') {
    labelWidth.value = '85'
  }
  if (data == 'zh-cn') {
    labelWidth.value = '51'
  }
})
defineExpose({
  returnLoginData
})
</script>

<style lang="less" scoped>
.login-account {
  .i18n {
    position: fixed;
    top: 20px;
    right: 60px;
  }
}
</style>
